import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { getCanvasCenter } from '../utils';

interface ImageSegment {
    id: string;
    material_id: string;
    target_timerange: {
        start: number;
        duration: number;
    };
    clip: {
        alpha: number;
        scale: { x: number; y: number };
        rotation: number;
        transform: { x: number; y: number };
        flip: { horizontal: boolean; vertical: boolean };
    };
    material_info: {
        id: string;
        name: string;
        public_url: string;
        width: number;
        height: number;
        duration: number;
    };
    currentTrackIndex?: number; // 当前轨道层级
}

interface ImageLayerProps {
    draftData: any;
    canvasWidth?: number; // 不再使用，但保留接口兼容性
    canvasHeight?: number; // 不再使用，但保留接口兼容性
}

// 判断是否为图片文件
const isImageFile = (url: string): boolean => {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
    const lowerUrl = url.toLowerCase();
    return imageExtensions.some((ext) => lowerUrl.includes(ext));
};

const ImageLayer: React.FC<ImageLayerProps> = ({ draftData }) => {
    const [imageSegments, setImageSegments] = useState<ImageSegment[]>([]);

    // 从Redux获取当前时间
    const currentTime = useSelector((state: RootState) => state.timeline.currentTime);

    // 提取图片片段数据
    useEffect(() => {
        if (!draftData?.script_content?.tracks) {
            setImageSegments([]);
            return;
        }

        const tracks = draftData.script_content.tracks;
        const segments: ImageSegment[] = tracks
            .filter((track: any) => track.type === 'video' && track.segments)
            .flatMap((track: any, trackIndex: number) =>
                track.segments
                    .filter((segment: any) => segment.material_info && segment.material_info.public_url && isImageFile(segment.material_info.public_url))
                    .map((segment: any) => ({
                        ...segment,
                        currentTrackIndex: trackIndex,
                    }))
            )
            .map((segment: any) => ({
                id: segment.id,
                material_id: segment.material_id,
                target_timerange: segment.target_timerange,
                clip: segment.clip,
                material_info: segment.material_info,
                currentTrackIndex: segment.currentTrackIndex,
            }));

        setImageSegments(segments);
    }, [draftData]);

    // 使用 calcMaterialSize 计算图片尺寸和位置
    const getImageStyle = (segment: ImageSegment) => {
        // 根据轨道层级设置 zIndex，层级越大的显示在上层
        // 图片图层基础zIndex为2000，确保在视频图层之上
        const zIndex = segment.currentTrackIndex || 0;
        console.log(`图片素材的zindex`, zIndex);

        // 获取画布中心位置
        const canvasCenter = getCanvasCenter();
        console.log('图片画布中心', canvasCenter);

        // 计算图片占满画布的尺寸
        const fullCanvasWidth = canvasCenter.x * 2; // 画布宽度
        const fullCanvasHeight = canvasCenter.y * 2; // 画布高度

        // 基础样式 - 默认占满整个画布
        const baseStyle = {
            position: 'absolute' as const,
            backgroundColor: 'transparent' as const,
            width: `${fullCanvasWidth}px`,
            height: `${fullCanvasHeight}px`,
            zIndex: zIndex,
        };

        // 只有当 clip 存在时才处理位置和变换
        if (segment.clip) {
            // 根据 transform 值计算偏移量
            const offsetX = (segment.clip.transform.x || 0) * 100;
            const offsetY = (segment.clip.transform.y || 0) * 1000;

            // 计算最终位置 - 减去元素自身尺寸的一半，让元素真正居中
            const finalX = canvasCenter.x + offsetX - fullCanvasWidth / 2;
            const finalY = canvasCenter.y + offsetY - fullCanvasHeight / 2;

            // 构建变换字符串 - 按正确顺序应用变换
            const transforms = [];

            // 1. 先应用缩放
            if (segment.clip.scale) {
                transforms.push(`scale(${segment.clip.scale.x || 1}, ${segment.clip.scale.y || 1})`);
            }

            // 2. 再应用旋转
            if (segment.clip.rotation) {
                transforms.push(`rotate(${segment.clip.rotation}deg)`);
            }

            // 3. 最后应用翻转
            if (segment.clip.flip) {
                const scaleX = segment.clip.flip.horizontal ? -1 : 1;
                const scaleY = segment.clip.flip.vertical ? -1 : 1;
                transforms.push(`scale(${scaleX}, ${scaleY})`);
            }

            return {
                ...baseStyle,
                left: `${finalX}px`,
                top: `${finalY}px`,
                opacity: segment.clip.alpha || 1, // 使用 clip 中的 alpha 值
                transform: transforms.length > 0 ? transforms.join(' ') : undefined,
                transformOrigin: 'center center',
            };
        }

        // 没有 clip 时使用默认定位（画布中心）
        return {
            ...baseStyle,
            left: `${canvasCenter.x - fullCanvasWidth / 2}px`, // 减去图片宽度的一半
            top: `${canvasCenter.y - fullCanvasHeight / 2}px`, // 减去图片高度的一半
            opacity: 1, // 默认完全不透明
        };
    };

    return (
        <div
            style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: 'transparent',
                zIndex: 2,
            }}
        >
            {imageSegments.map((segment) => {
                // 计算是否应该显示
                const startTime = segment.target_timerange.start / 1000;
                const endTime = startTime + segment.target_timerange.duration / 1000;
                const shouldShow = currentTime >= startTime && currentTime <= endTime;

                if (!shouldShow) return null;

                const imageStyle = getImageStyle(segment);

                return (
                    <img
                        key={segment.id}
                        src={segment.material_info.public_url}
                        alt={segment.material_info.name}
                        style={{
                            ...imageStyle,
                            objectFit: 'cover', // 确保图片填充整个区域
                            objectPosition: 'center', // 图片居中显示
                        }}
                        draggable={false}
                    />
                );
            })}
        </div>
    );
};

export default ImageLayer;
